package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.GreFileLogic;
import cn.topevery.garden.dal.logic.TaskOnSiteLogic;
import cn.topevery.garden.dal.logic.TaskPointLogic;
import cn.topevery.garden.dal.logic.TaskUserLogic;
import cn.topevery.garden.entity.dto.TaskOnSiteDTO;
import cn.topevery.garden.entity.po.GreFile;
import cn.topevery.garden.entity.po.TaskOnSite;
import cn.topevery.garden.entity.po.TaskPoint;
import cn.topevery.garden.entity.po.TaskUser;
import cn.topevery.garden.entity.query.TaskOnSiteQuery;
import cn.topevery.garden.entity.vo.TaskDocumentVO;
import cn.topevery.garden.entity.vo.TaskOnSiteVO;
import cn.topevery.garden.entity.vo.TaskUserVO;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 现场检查
 */
@Api(tags = "现场检查")
@RestController
@RequestMapping("/taskOnSite")
public class TaskOnSiteController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    TaskOnSiteLogic taskOnSiteLogic;

    @Autowired
    TaskUserLogic taskUserLogic;

    @Autowired
    TaskPointLogic taskPointLogic;

    @Autowired
    GreFileLogic greFileLogic;

    @Autowired
    SysUserLogic sysUserLogic;


    /**
     * 获取现场检查分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取现场检查页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<TaskOnSiteVO>> listPage(@RequestBody TaskOnSiteQuery query) {
        DataPager<TaskOnSiteVO> page = taskOnSiteLogic.listPage(query);
        for (TaskOnSiteVO taskOnSiteVO : page.records) {
            taskOnSiteVO.setFileList(greFileLogic.getListByMainId(taskOnSiteVO.getId(), GreFile.TYPE_TASK_ON_SITE));
            taskOnSiteVO.setAnswerFileList(greFileLogic.getListByMainId(taskOnSiteVO.getId(), GreFile.TYPE_TASK_ON_SITE_ANSWER));
            taskOnSiteVO.setPointList(taskPointLogic.listByTaskIdOrUserId(taskOnSiteVO.getId(), null));
            // 绑定考评人员
            List<TaskUserVO> taskUserVOS = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_ON_SITE, taskOnSiteVO.getId(), null);
            bindEvaluationUser(taskOnSiteVO, taskUserVOS);
        }
        return JsonResult.ok(page);
    }

    private void bindEvaluationUser(TaskOnSiteVO taskOnSiteVO, List<TaskUserVO> taskUserVOS) {
        Integer[] userIds = taskUserVOS.stream().map(TaskUserVO::getEvaluationUserId).toArray(Integer[]::new);
        List<SysUser> userList = sysUserLogic.getEntitys(userIds);
        List<SysUser> res = new ArrayList<>();
        for (SysUser user : userList) {
            SysUser resUser = new SysUser();
            resUser.id = user.id;
            resUser.userId = user.userId;
            resUser.userName = user.userName;
            res.add(resUser);
        }
        taskOnSiteVO.setEvaluationUserList(res);
    }

    @ApiOperation("新增/编辑 现场检查信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody TaskOnSiteDTO dto) {
        String userId = getUser().id.toString();
        TaskOnSite taskOnSite = mapper.map(dto, TaskOnSite.class);
        taskOnSiteLogic.saveOrUpdate(getUser().id.toString(), taskOnSite);
        dto.setId(taskOnSite.getId());
        // 删去旧的考评人员关联
        List<TaskUserVO> taskUserVOList = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_ON_SITE, dto.getId(), null);
        if (!taskUserVOList.isEmpty()) {
            Integer[] ids = taskUserVOList.stream().map(TaskUserVO::getId).toArray(Integer[]::new);
            taskUserLogic.deleteBatchById(userId, ids);
        }
        // 新增考评人员关联
        List<SysUser> evaluationUserList = dto.getEvaluationUserList();
        if (!CollectionUtils.isEmpty(evaluationUserList)) {
            List<TaskUser> taskUserList = new ArrayList<>();
            for (SysUser user : evaluationUserList) {
                TaskUser taskUser = new TaskUser();
                taskUser.taskId = dto.getId();
                taskUser.evaluationUserId = user.id;
                taskUser.taskType = TaskUser.TYPE_TASK_ON_SITE;
                taskUserList.add(taskUser);
            }
            taskUserLogic.insert(userId, taskUserList);
        }
        // 删去旧的样点关联
        List<TaskPoint> taskPointVOList = taskPointLogic.listByTaskIdOrUserId(dto.getId(), null);
        if (!CollectionUtils.isEmpty(taskPointVOList)) {
            Integer[] oldPointIdList = taskPointVOList.stream().map(TaskPoint::getId).toArray(Integer[]::new);
            taskPointLogic.deleteBatchById(userId, oldPointIdList);
        }
        // 新增样点关联
        List<TaskPoint> newPointList = dto.getPointList();
        if (!CollectionUtils.isEmpty(newPointList)) {
            for (TaskPoint taskPoint : newPointList) {
                taskPoint.setTaskId(dto.getId());
                taskPoint.setLostScoreContent("");
            }
            taskPointLogic.insert(userId, newPointList);
        }
        // 删去旧的文件关联
        List<GreFile> oldFileList = greFileLogic.getListByMainId(dto.getId(), GreFile.TYPE_TASK_ON_SITE);
        if (!CollectionUtils.isEmpty(oldFileList)) {
            Integer[] oldFileIdList = oldFileList.stream().map(GreFile::getId).toArray(Integer[]::new);
            greFileLogic.deleteBatchById(userId, oldFileIdList);
        }
        // 新增文件关联
        List<GreFile> newFileList = dto.getFileList();
        if (!CollectionUtils.isEmpty(newFileList)) {
            for (GreFile greFile : newFileList) {
                greFile.mainId = dto.getId();
                greFile.setDataType(GreFile.TYPE_TASK_ON_SITE);
            }
            greFileLogic.insert(userId, newFileList);
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult<TaskOnSiteVO> getInfoById(@RequestParam Integer id) {
        TaskOnSite entity = taskOnSiteLogic.getEntity(id);
        TaskOnSiteVO vo = mapper.map(entity, TaskOnSiteVO.class);
        vo.setFileList(greFileLogic.getListByMainId(id, GreFile.TYPE_TASK_ON_SITE));
        vo.setAnswerFileList(greFileLogic.getListByMainId(id, GreFile.TYPE_TASK_ON_SITE_ANSWER));
        vo.setPointList(taskPointLogic.listByTaskIdOrUserId(id, null));
        // 绑定考评人员
        List<TaskUserVO> taskUserVOS = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_ON_SITE, id, null);
        bindEvaluationUser(vo, taskUserVOS);
        return JsonResult.ok(vo);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        taskOnSiteLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出现场检查信息")
    @GetMapping("/export")
    public void export(TaskOnSiteQuery query, HttpServletResponse response) {
        List<TaskOnSiteVO> list = taskOnSiteLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "现场检查", "sheet1", TaskOnSiteVO.class, "现场检查", response);
    }

    @ApiOperation("填报任务")
    @PostMapping("saveMyTask")
    @Transactional
    public JsonResult saveMyTask(@RequestBody TaskOnSiteVO taskOnSiteVO) {
        SysUser currentUser = getUser();
        String userId = currentUser.id.toString();
        // 更新样点信息
        List<TaskPoint> pointList = taskOnSiteVO.getPointList();
        for (TaskPoint taskPoint : pointList) {
            taskPointLogic.saveOrUpdate(userId, taskPoint);
        }
        TaskOnSite entity = taskOnSiteLogic.getEntity(taskOnSiteVO.getId());
        entity.setFinished(true);
        entity.setCheckTime(taskOnSiteVO.getCheckTime());
        entity.setEvaluationUserId(currentUser.id);
        entity.setEvaluationUserName(currentUser.userName);
        int score = pointList.stream().map(TaskPoint::getLostScore).mapToInt(Integer::intValue).sum();
        entity.setScore(score);
        taskOnSiteLogic.saveOrUpdate(userId, entity);

        // 删去旧的文件关联
        List<GreFile> oldFileList = greFileLogic.getListByMainId(taskOnSiteVO.getId(), GreFile.TYPE_TASK_ON_SITE_ANSWER);
        if (!CollectionUtils.isEmpty(oldFileList)) {
            Integer[] oldFileIdList = oldFileList.stream().map(GreFile::getId).toArray(Integer[]::new);
            greFileLogic.deleteBatchById(userId, oldFileIdList);
        }
        // 新增文件关联
        List<GreFile> newFileList = taskOnSiteVO.getFileList();
        if (!CollectionUtils.isEmpty(newFileList)) {
            for (GreFile greFile : newFileList) {
                greFile.mainId = taskOnSiteVO.getId();
                greFile.setDataType(GreFile.TYPE_TASK_ON_SITE_ANSWER);
            }
            greFileLogic.insert(userId, newFileList);
        }
        return JsonResult.ok();
    }

    @ApiOperation("删除我的填报")
    @GetMapping("deleteMyFinished")
    public JsonResult deleteMyFinished(TaskDocumentVO taskDocumentVO) {
        String userId = getUser().id.toString();
        TaskOnSite taskOnSite = taskOnSiteLogic.getEntity(taskDocumentVO.getId());
        // 将任务重置为未填报
        taskOnSite.setFinished(false);
        taskOnSite.setCheckTime(null);
        taskOnSite.setScore(null);
        taskOnSiteLogic.saveOrUpdate(userId, taskOnSite);
        // 删除填报的附件
        List<GreFile> answerFileList = greFileLogic.getListByMainId(taskOnSite.getId(), GreFile.TYPE_TASK_ON_SITE_ANSWER);
        Integer[] answerFileIdList = answerFileList.stream().map(GreFile::getId).toArray(Integer[]::new);
        if (!CollectionUtils.isEmpty(answerFileList)) {
            greFileLogic.deleteBatchById(userId, answerFileIdList);
        }

        // 删除评分信息
        List<TaskPoint> taskPointList = taskPointLogic.listByTaskIdOrUserId(taskOnSite.getId(), null);
        taskPointList.forEach(taskPoint -> {
            taskPoint.setLostScore(0);
            taskPoint.setLostScoreContent("");
            taskPointLogic.saveOrUpdate(userId, taskPoint);
        });
        return JsonResult.ok();
    }

    @ApiOperation("获得我的任务或已填报")
    @GetMapping("listMyTask")
    public JsonResult listMyTask(TaskOnSiteQuery query) {
        Integer currentUserId = getUser().id;
        query.setTaskOfUserId(currentUserId);
        DataPager<TaskOnSiteVO> page = taskOnSiteLogic.listPage(query);
        for (TaskOnSiteVO taskOnSiteVO : page.records) {
            taskOnSiteVO.setFileList(greFileLogic.getListByMainId(taskOnSiteVO.getId(), GreFile.TYPE_TASK_ON_SITE));
            taskOnSiteVO.setAnswerFileList(greFileLogic.getListByMainId(taskOnSiteVO.getId(), GreFile.TYPE_TASK_ON_SITE_ANSWER));
            taskOnSiteVO.setPointList(taskPointLogic.listByTaskIdOrUserId(taskOnSiteVO.getId(), null));
            // 绑定考评人员
            List<TaskUserVO> taskUserVOS = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_ON_SITE, taskOnSiteVO.getId(), null);
            bindEvaluationUser(taskOnSiteVO, taskUserVOS);
        }
        return JsonResult.ok(page);
    }

}
